﻿using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Messaging.Messages;
using Nett;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Documents;
using System.Windows.Input;
using 收入分析.Model;

namespace 收入分析.Services;
internal class SystemManager : Repository<AppData> {
    // GameMaster
    public static SystemManager GM { get { return db.Value; } }
    private static readonly Lazy<SystemManager> db = new(() => new SystemManager(), true);
    private static readonly object locker = new();//创建锁

    private readonly Version? _version;

    private AppData _appdata;
    public Config Config { get; set; }

    private SystemManager() {
        // 获取程序版本号
        _version = Assembly.GetExecutingAssembly().GetName().Version;
        Debug.WriteLine(new DateTime(2000, 1, 1).AddDays(_version?.Build ?? 0));
        Config = Toml.ReadFile<Config>("Config.toml");
        //var tables = Db.DbMaintenance.GetTableInfoList(false);//true 走缓存 false不走缓存
        // 检查系统数据库
        if (!Db.DbMaintenance.IsAnyTable("sys_app_data")) {
            if (!CreateAppDataTable()) return;
        }
        try {
            _appdata = GetFirst(x => true);
        }
        catch (Exception) {
            _appdata = new();
        }
    }
    private bool CreateAppDataTable() {
        try {
            lock (locker) {
                Db.CodeFirst.SetStringDefaultLength(20).InitTables<AppData>();
                AsInsertable(new AppData() {
                    DefaultAnylysisTable = "latest",
                    DefaultLastYearDataTable = "latest",
                    DBTypeList = Enum.GetNames(typeof(DataBaseType)).ToList(),
                    Tables = new(),
                }).ExecuteCommand();
                return true;
            }
        }
        catch (Exception e) {
            Debug.WriteLine(e.Message);
            return false;
        }
    }
    internal async Task<int> AddTableInfomationAsync(DataTableInfo info) {
        info.Id = _appdata.Tables.Count + 1;
        _appdata.Tables.Add(info);
        return await AsUpdateable(_appdata).UpdateColumns(x => x.Tables).ExecuteCommandAsync();
    }

    internal List<string> DataBaseList => _appdata.Tables.Select(x => x.Name).ToList();
    internal List<DataTableInfo> TablesInfoList => _appdata.Tables;
    internal static DataBaseType? GetDataBaseType(string db) {
        try {
            if (Enum.TryParse(db.AsSpan(0, db.IndexOf('_')),
                out DataBaseType t))
                return t;

        }
        catch (Exception) {
            Debug.WriteLine("转换失败");
        }
        return null;
    }
    internal static void PostStatusBarMessage(StatusBarMessage _data) {
        WeakReferenceMessenger.Default.Send(new ValueChangedMessage<StatusBarMessage>(_data), "token_status_bar_msg");
    }
    internal static void PostStatusBarMessage(string _data) {
        PostStatusBarMessage(new StatusBarMessage() { Message = _data });
    }

    internal class StatusBarMessage {
        public string Message { get; set; }
    }
    //全字段2021,
    //全字段2022,
    //全字段2023,
    //系统收入2021,
    //系统收入2022,
    //系统收入2023,
    //采集收入2022,
    //采集收入2023,
}
